package org.fixed.dubboconsumer.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.web.servlet.error.DefaultErrorViewResolver;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 〈一句话功能简述>
 * ${DESCRIPTION}
 * Author:xuzhongwei
 * Date:2018/12/28
 */
@Controller
public class IndexController {

    @Autowired
    private ApplicationContext applicationContext;

    @Value("${spring.thymeleaf.prefix}")
    private String thymeleafPrefix;

    /**
     * 默认跳转首页
     * @return
     */
    @RequestMapping("/")
    public String index() {
        return "index";
    }
    /**
     * 跳转首页
     * @return
     */
    @RequestMapping(value = "/index")
    public String index1() {
        return "index";
    }

    @RequestMapping(value = "/view/**")
    public ModelAndView turnTo(HttpServletRequest request) throws IOException {
        String url = StringUtils.replace(request.getRequestURI(),"/view","");
        if(StringUtils.isEmpty(url) || "/".equals(url)){
            return new ModelAndView("index");
        }
        Resource resource = this.applicationContext.getResource(thymeleafPrefix);
        resource = resource.createRelative(url + ".html");
        if (resource.exists()) {
            return new ModelAndView(org.apache.commons.lang.StringUtils.removeStart(url,"/"));
        }
        Map<String, Object> model = new HashMap<>();
        model.put("path",url);
        model.put("message","No message available");
        model.put("status","404");
        return new ModelAndView("error/error",model);
    }

}
